package com.hk.service.order.impl;

import java.math.BigDecimal;
import java.net.URI;
import java.sql.Timestamp;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.hk.commons.*;
import com.hk.commons.enm.ConfirmStatusEnum;
import com.hk.commons.entity.ActiveOrderRecord;
import com.hk.commons.entity.Parameter;
import com.hk.commons.entity.UserChannel;
import com.hk.commons.entity.product.Company;
import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.entity.sys.UserChangeInfo;
import com.hk.commons.utils.sys.DataHelper;
import com.hk.commons.utils.sys.DateHelper;
import com.hk.commons.vo.CheckInfo;
import com.hk.service.IActiveOrderRecord;
import com.hk.service.IUserChannel;
import com.hk.service.message.CouponJsonResult;
import com.hk.service.message.CouponResult;
import com.hk.service.message.CouponWalletReq;
import com.hk.service.order.*;
import com.hk.service.product.ICompany;
import com.hk.service.sys.ISysUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.hk.commons.enm.CompanyEnum;
import com.hk.commons.enm.PayStatusEnum;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.order.OrderRouteInfo;
import com.hk.commons.entity.view.OrderView;
import com.hk.commons.entity.yingmi.YingmiOrderFile;
import com.hk.commons.utils.order.OrderCreateMsg;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.commons.vo.OrderStrMsg;
import com.hk.service.product.IProductInfo;
import com.hk.service.view.IOrderView;

@Service
public class OrderHandleContent {

	@Resource(name = "yingmiOrderHandleImpl")
	private IOrderHandle<YingmiOrderFile> yingmiOrderHandleImpl;

	@Resource(name = "hkOrderHandleImpl")
	private IOrderHandle<OrderInfo> hkOrderHandleImpl;

	@Resource(name = "huochaiOrderImpl")
	private IOrderHandle<OrderCreateMsg> huochaiOrderImpl;

	@Autowired
	private IOrderInfo orderService;

	@Autowired
	private IPayment paymentService;


	@Autowired
	private YingmiApiUtils yingmiUtils;

	@Autowired
	private IUserChannel userChannelService;

	@Autowired
	private IProductInfo productService;

	@Autowired
	private IOrderRouteInfo orderRouteService;

	@Autowired
	private ISysUser userService;

	@Autowired
	private ICompany companyServie;

	@Autowired
	private IOrderView orderViewService;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private IActiveOrderRecord activeOrderRecordService;

	@Autowired
	private IParameter parameterService;


	@Autowired
	private IParameter parmService;

	@Value("${activity.baseUrl}")
	private String host;

	private static final String ThreeEndEncourage = "ThreeEndEncourage";
	private static final String OneDayEncourage = "OneDayEncourage";
	private static final String ThreeComboEncourage = "ThreeComboEncourage";

	private static final String ThreeEndUser = "ThreeEndUser";
	private static final String WhatNumberEnd = "WhatNumberEnd";
	private static final String OneDayEncourageMoney = "OneDayEncourageMoney";
	private static final String ThreeComboEncourageMoney = "ThreeComboEncourageMoney";
	private static final String ThreeComboEncourageTime = "ThreeComboEncourageTime";

	private static final String WYDATETIME = "yyyyMMddkkmmss";

	private static final String WYDATE = "yyyyMMdd";

	private Logger logger = LoggerFactory.getLogger(OrderHandleContent.class);

	//没有用
	public List<?> findAll(int routeId) {
		HqlFilter hqlFilter = new HqlFilter();
		List<?> list = new ArrayList<>();
		switch (routeId) {
		case ConstantRoute.COMPANY_HUAKANG:
			list = hkOrderHandleImpl.query(hqlFilter);
			break;
		case ConstantRoute.COMPANY_HUOCHAI:
			break;
		case ConstantRoute.COMPANY_YINGMI:
			list = yingmiOrderHandleImpl.query(hqlFilter);
			break;
		}
		return list;

	}

	/**
	 * 查询并更新redis 中所有火柴的订单
	 */
	public void checkAllOrderInRedis() {
		huochaiOrderImpl.checkAllOrderInRedis();
	}

	/**
	 * 获取异常订单，目前只针对火柴
	 *
	 * @return
	 */

	public List<OrderStrMsg> getAllExceptionOrder() {

		List<OrderStrMsg> exceptionOrderList = new ArrayList<OrderStrMsg>();

		exceptionOrderList = huochaiOrderImpl.getAllExceptionOrder();

		return exceptionOrderList;
	}

	/**
	 * 检查火柴异常订单列表
	 * @return
	 */
	public Boolean reCheckHCOrder() {
		List<OrderStrMsg> orderExcepitonList = getAllExceptionOrder();
		for (OrderStrMsg orderInfoMsg : orderExcepitonList) {
			Long orderId = Long.valueOf(orderInfoMsg.getId());
			Long userId = Long.valueOf(orderInfoMsg.getUserId());
			huochaiOrderImpl.updOrderInfo(userId, orderId);
		}
		return true;
	}

	public List<OrderStrMsg> getAll(Long userId) {
		//userId = CheckUserId.checkId(userId);
		List<OrderStrMsg> orderList = new ArrayList<OrderStrMsg>();

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("userId", userId);
		hqlFilter.addSort("cts");
		hqlFilter.addOrder("desc");
		List<OrderRouteInfo> orderRouteList = orderRouteService
				.findByFilter(hqlFilter);
		for (OrderRouteInfo orderRouteInfo : orderRouteList) {
			Integer routeId = orderRouteInfo.getCompanyId();

			Long orderId = orderRouteInfo.getOrderId();

			/*
			 * logger.info("getAll userId = " + userId + "  orderId = " +
			 * orderId + "  routeId = " + routeId);
			 */
			OrderStrMsg orderStrMsg = new OrderStrMsg();

			/*
			switch (routeId) {
			case ConstantRoute.COMPANY_HUAKANG:
				orderStrMsg = hkOrderHandleImpl.getStrInfoById(orderId);
				break;
			case ConstantRoute.COMPANY_HUOCHAI:
				orderStrMsg = huochaiOrderImpl.getStrInfoById(userId, orderId);
				break;
			*/
			if (routeId == ConstantRoute.COMPANY_HUOCHAI) {
				orderStrMsg = huochaiOrderImpl.getStrInfoById(userId, orderId);
			}else{
				orderStrMsg = hkOrderHandleImpl.getStrInfoById(orderId);
			}
			/*
			 * case ConstantRoute.COMPANY_YINGMI: orderStrMsg =
			 * yingmiOrderHandleImpl.getStrInfoById(orderId ); break;
			 */

			
			/*
			if (orderStrMsg != null
					&& StringHelper.isNotEmpty(orderStrMsg.getPayStatus())
					&& (!orderStrMsg.getConfirmStatus().equals("3"))){
				orderList.add(orderStrMsg);
			}
			*/
			
			if (orderStrMsg != null
					&& StringHelper.isNotEmpty(orderStrMsg.getPayStatus())
					&&  StringHelper.isNotEmpty(orderStrMsg.getConfirmStatus())){
				orderList.add(orderStrMsg);
			}

		}
		return orderList;

	}

	public List<OrderStrMsg> getAllVersion2(Long userId, Integer pageSize, Long orderTimestamp) {
		List<OrderStrMsg> orderList = new ArrayList<>();

		Timestamp timestamp = null;

		LocalDate localDate = null;
		LocalDate thisMonth = null;
		LocalDateTime localDateTime = null;

		if (orderTimestamp == -1) {
			localDate = LocalDate.now();
			thisMonth = LocalDate.of(localDate.getYear(), localDate.getMonth().getValue(), 1);
			localDateTime = LocalDateTime.of(thisMonth, LocalTime.of(0, 0));
			timestamp = Timestamp.valueOf(localDateTime);
		} else {
			timestamp = Timestamp.from(Instant.ofEpochMilli(orderTimestamp));

			localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(orderTimestamp), ZoneId.of("Asia/Shanghai"));
			thisMonth = LocalDate.of(localDateTime.getYear(), localDateTime.getMonth().getValue(), 1);
		}


		HqlFilter hqlFilter = new HqlFilter();
		if (orderTimestamp == -1) {
			hqlFilter.addEQFilter("userId", userId);
			hqlFilter.addFilter("cts", "L", "GE", String.valueOf(timestamp.getTime()));
			hqlFilter.addSort("cts");
			hqlFilter.addOrder("desc");
		} else {
			hqlFilter.addEQFilter("userId", userId);
			hqlFilter.addFilter("cts", "L", "LT", String.valueOf(orderTimestamp));
			hqlFilter.addFilter("cts", "L", "GE", String.valueOf(Timestamp.valueOf(localDateTime).getTime()));
			hqlFilter.addSort("cts");
			hqlFilter.addOrder("desc");
		}


		List<OrderRouteInfo> orderRouteList = orderRouteService.findByFilter(hqlFilter);
		LocalDate firstDate = LocalDate.of(2016, 1, 1);

		while (orderRouteList.size() < pageSize && thisMonth.compareTo(firstDate) > 0) {
			Timestamp thisTimestamp = timestamp;
			thisMonth = thisMonth.minusMonths(1L);
			localDateTime = LocalDateTime.of(thisMonth, LocalTime.of(0, 0));
			timestamp = Timestamp.valueOf(localDateTime);

			hqlFilter = new HqlFilter();
			hqlFilter.addEQFilter("userId", userId);
			hqlFilter.addFilter("cts", "L", "LT", String.valueOf(thisTimestamp.getTime()));
			hqlFilter.addFilter("cts", "L", "GE", String.valueOf(timestamp.getTime()));
			hqlFilter.addSort("cts");
			hqlFilter.addOrder("desc");

			List<OrderRouteInfo> results = orderRouteService.findByFilter(hqlFilter);

			if (results.size() > 0) {
				orderRouteList.addAll(results);
			}
		}

		for (OrderRouteInfo orderRouteInfo : orderRouteList) {
			Integer routeId = orderRouteInfo.getCompanyId();

			Long orderId = orderRouteInfo.getOrderId();

			OrderStrMsg orderStrMsg = null;

			if (routeId == ConstantRoute.COMPANY_HUOCHAI) {
				orderStrMsg = huochaiOrderImpl.getStrInfoById(userId, orderId);
			}else{
				orderStrMsg = hkOrderHandleImpl.getStrInfoById(orderId);
			}

			if (orderStrMsg != null
					&& StringHelper.isNotEmpty(orderStrMsg.getPayStatus())
					&&  StringHelper.isNotEmpty(orderStrMsg.getConfirmStatus())){
				orderList.add(orderStrMsg);
			}

		}
		return orderList;

	}

	//根据确认状态获取订单信息
	public List<OrderStrMsg> getAll(Long userId, Integer confirmStatus) {
		//userId = CheckUserId.checkId(userId);
		List<OrderStrMsg> orderList = new ArrayList<OrderStrMsg>();

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1 = 1 and t.userId = " + userId + " and t.orderId in (select s.id from com.hk.commons.entity.order.OrderInfo s where s.confirmStatus = "+ confirmStatus +  ") order by t.cts desc");
		//hqlFilter.addSort("cts");
		//hqlFilter.addOrder("desc");
		
		
		logger.info("sql = " + hqlFilter.getWhereAndOrderHql());
		
		List<OrderRouteInfo> orderRouteList = orderRouteService
				.findByFilter(hqlFilter);
		for (OrderRouteInfo orderRouteInfo : orderRouteList) {
			Integer routeId = orderRouteInfo.getCompanyId();

			Long orderId = orderRouteInfo.getOrderId();
			OrderStrMsg orderStrMsg = new OrderStrMsg();

			/*
			switch (routeId) {
			case ConstantRoute.COMPANY_HUAKANG:
				orderStrMsg = hkOrderHandleImpl.getStrInfoById(orderId);
				break;
			case ConstantRoute.COMPANY_HUOCHAI:
				orderStrMsg = huochaiOrderImpl.getStrInfoById(userId, orderId);
				break;
			
			}
			*/

			if (routeId == ConstantRoute.COMPANY_HUOCHAI) {
				orderStrMsg = huochaiOrderImpl.getStrInfoById(userId, orderId);
			}else{
				orderStrMsg = hkOrderHandleImpl.getStrInfoById(orderId);
			}

			if (orderStrMsg != null
					&& StringHelper.isNotEmpty(orderStrMsg.getPayStatus())
					&&  StringHelper.isNotEmpty(orderStrMsg.getConfirmStatus())){
				orderList.add(orderStrMsg);
			}

		}
		return orderList;
	}

	/**
	 * 获取所有的订单信息，包含盈米的
	 * 
	 * @param userId
	 * @return
	 */

	public List<OrderStrMsg> getAllOrderMessage(Long userId) {
		//userId = CheckUserId.checkId(userId);
		List<OrderStrMsg> orderList = new ArrayList<OrderStrMsg>();

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("userId", userId);
		hqlFilter.addSort("cts");
		hqlFilter.addOrder("desc");
		List<OrderRouteInfo> orderRouteList = orderRouteService
				.findByFilter(hqlFilter);
		for (OrderRouteInfo orderRouteInfo : orderRouteList) {
			Integer routeId = orderRouteInfo.getCompanyId();

			Long orderId = orderRouteInfo.getOrderId();

			/*
			 * logger.info("getAll userId = " + userId + "  orderId = " +
			 * orderId + "  routeId = " + routeId);
			 */
			OrderStrMsg orderStrMsg = new OrderStrMsg();

			/*
			switch (routeId) {
			case ConstantRoute.COMPANY_HUAKANG:
				orderStrMsg = hkOrderHandleImpl.getStrInfoById(orderId);
				break;
			case ConstantRoute.COMPANY_HUOCHAI:
				orderStrMsg = huochaiOrderImpl.getStrInfoById(userId, orderId);
				break;

			case ConstantRoute.COMPANY_YINGMI:
				orderStrMsg = yingmiOrderHandleImpl.getStrInfoById(orderId);
				break;

			}
			*/

			if (routeId == ConstantRoute.COMPANY_HUOCHAI) {
				orderStrMsg = huochaiOrderImpl.getStrInfoById(userId, orderId);
			}else if (routeId == ConstantRoute.COMPANY_YINGMI) {
				orderStrMsg = huochaiOrderImpl.getStrInfoById(userId, orderId);
			}else{
				orderStrMsg = hkOrderHandleImpl.getStrInfoById(orderId);
			}




			if (orderStrMsg != null
					&& StringHelper.isNotEmpty(orderStrMsg.getPayStatus())) {
				orderList.add(orderStrMsg);
			}

		}
		return orderList;

	}

	/**
	 * 获取所有已支付的订单
	 * 
	 * @param userId
	 * @return
	 */
	public OrderStrMsg getOrderInfo(Long orderId, Long userId, Integer routeId) {

		OrderStrMsg orderStrMsg = new OrderStrMsg();

		if (ConstantRoute.COMPANY_YINGMI == routeId) {
			orderStrMsg = yingmiOrderHandleImpl.getStrInfoById(orderId);
		} else {
			OrderView orderView = orderViewService.findById(orderId);
			if(orderView!=null){
				orderStrMsg = getOrderStrMsgByView(orderView);
			}			
		}

		return orderStrMsg;
	}

	public List<?> findByOrderId(OrderRouteInfo or) {
		List<?> list = new ArrayList<>();
		switch (or.getCompanyId()) {
		case ConstantRoute.COMPANY_YINGMI:
			HqlFilter yiFilter = new HqlFilter();
			yiFilter.addEQFilter("brokerOrderNo", or.getBrokerOrderNo());
			list = yingmiOrderHandleImpl.query(yiFilter);
			if (list.size() == 0) {
				String path = "/trade/getFundOrder";
				Map<String, String> params = new HashMap<>();
				String result = this.yingmiUtils.get(path, params);
			}

			break;
		case ConstantRoute.COMPANY_HUOCHAI:
			break;
		}

		return list;
	}

	/**
	 * 重新检查订单的信息
	 * 
	 * @param orderId
	 * @param routeId
	 * @return
	 */

	public Boolean reCheckOrderStatus(Long userId, Long orderId, Integer routeId) {
		logger.info("OrderHandleContent will check order: order id = "
				+ orderId + " companyId = " + routeId);
		Boolean result = false;
		switch (routeId) {
		case ConstantRoute.COMPANY_HUAKANG:
			result = hkOrderHandleImpl.reCheck(userId, orderId);
			break;
		case ConstantRoute.COMPANY_HUOCHAI:
			result = huochaiOrderImpl.reCheck(userId, orderId);
			break;
		case ConstantRoute.COMPANY_YINGMI:
			result = yingmiOrderHandleImpl.reCheck(userId, orderId);
			break;
		}
		return result;
	}

	// 火柴订单创建
	public OrderCreateMsg create(Long productId, Long userId, Integer routeId,
			Long userCardId) {
		//userId = CheckUserId.checkId(userId);

		OrderCreateMsg resp = new OrderCreateMsg();
		// 添加公司属性
		resp.setCompanyId(routeId);

		if (routeId == ConstantRoute.COMPANY_HUOCHAI) {
			resp = huochaiOrderImpl.create(productId, userId, userCardId);
		}

		logger.info("will create new record userId = " + userId
				+ "  order id = " + resp.getOrderId());

		// 如果订单生成成功，则创建订单路由信息
		/*
		if (resp.getOrderId() != null) {
			createOrderRoute(userId, resp.getOrderId(), routeId);
		}
		*/

		logger.info("url = " + resp.getUrl() + "  buyInfo = " + resp.getInfo());
		return resp;
	}

	/**
	 * 链接富有通道进行支付
	 * 
	 * @param productId
	 * @param userId
	 * @param routeId
	 * @return
	 */

	//旧接口，已弃用
	public OrderCreateMsg createOrder(Long productId, Long userId,
			Integer routeId, Long paymentId, Long userCardId) {
		//userId = CheckUserId.checkId(userId);

		OrderCreateMsg resp = new OrderCreateMsg();
		// 添加公司属性
		resp.setCompanyId(routeId);

		switch (routeId) {
		case ConstantRoute.COMPANY_HUAKANG:
			resp = hkOrderHandleImpl.createOrder(productId, userId, paymentId,
					userCardId);
			break;
		case ConstantRoute.COMPANY_HUOCHAI:
			// 创建确认订单和订单流水

			// resp = huochaiOrderImpl.create(productId, userId);

			break;
		case ConstantRoute.COMPANY_YINGMI:
			break;
		}
		logger.info("will create new record userId = " + userId
				+ "  order id = " + resp.getOrderId());

		// 如果订单生成成功，则创建订单路由信息
		// if (resp.getOrderId() != null) {
		// createOrderRoute(userId, resp.getOrderId(), routeId);
		// }

		logger.info("url = " + resp.getUrl() + "  buyInfo = " + resp.getInfo());
		return resp;
	}

	/**
	 * 链接富有金账户进行支付
	 * 
	 * @param productId
	 * @param userId

	 * @return
	 */
	public OrderInfo createFYJZHOrder(Long orderId, Long userId,
			Long productId, Long userCardId, BigDecimal amount) {
		//userId = CheckUserId.checkId(userId);

		ProductInfo prod = productService.findById(productId);
		//Integer routeId = ConstantRoute.COMPANY_HUAKANG;
		if(prod == null || prod.getIssuerId() == null){
			return null;
		}

		Integer routeId = prod.getIssuerId();

		OrderInfo orderInfo = new OrderInfo();

		// 添加公司属性
		orderInfo.setCompanyId(routeId);

		orderInfo = hkOrderHandleImpl.createFYJZHOrder(productId, userId,
				userCardId, amount);

		System.out.println("order info in Hk is " + orderInfo);

		logger.info("will create new record userId = " + userId
				+ "  order id = " + orderInfo.getId());
		return orderInfo;
	}

	public Boolean updOrderInfo(Long userId, Long orderId, Integer routeId) {
		Boolean result = false;
		switch (routeId) {
		case ConstantRoute.COMPANY_HUAKANG:

			break;
		case ConstantRoute.COMPANY_HUOCHAI:

			result = huochaiOrderImpl.updOrderInfo(userId, orderId);
			break;
		case ConstantRoute.COMPANY_YINGMI:

			break;
		}

		return result;
	}

	public Long createOrderRoute(Long userId, Long orderId, Integer routeId) {

		/*
		switch (routeId) {
		case ConstantRoute.COMPANY_HUAKANG:
			hkOrderHandleImpl.createOrderRoute(userId, orderId, routeId);
			break;
		case ConstantRoute.COMPANY_HUOCHAI:
			huochaiOrderImpl.createOrderRoute(userId, orderId, routeId);
			break;
		case ConstantRoute.COMPANY_YINGMI:

			break;
		}
		*/
		OrderInfo orderInfo = orderService.findById(orderId);
		if(orderInfo == null){
			return  null;
		}
		OrderRouteInfo orderRouteInfo = new OrderRouteInfo();
		orderRouteInfo.setUserId(userId);
		orderRouteInfo.setCompanyId(routeId);
		orderRouteInfo.setOrderId(orderId);
		if(routeId == ConstantRoute.COMPANY_HUAKANG){
			orderRouteInfo.setBrokerOrderNo("hk" + orderId);
		}else if(routeId == ConstantRoute.COMPANY_HUOCHAI) {
			orderRouteInfo.setBrokerOrderNo("hc" + orderId);
		}else{
			orderRouteInfo.setBrokerOrderNo(routeId + orderId.toString());
		}
		// orderRouteInfo.setProductId(orderInfo.getId());
		orderRouteInfo.setProductId(orderInfo.getProductId());

		SysUser user = userService.findById(userId);
		if (user != null && StringHelper.isNotEmpty(user.getRecommendCode())) {
			SysUser finUser = userService
					.getByPhoneNum(user.getRecommendCode());
			if (finUser != null) {
				orderRouteInfo.setFinancialPlannerId(finUser.getId());
			}

			if (StringHelper.isNotEmpty(user.getAccountId())) {
				orderRouteInfo.setAccountId(user.getAccountId());
			}
		}

		orderRouteService.add(orderRouteInfo);

		return orderId;
	}

	/**
	 * 检查是不是专项标的第3、13、23、33...93笔（共计10笔）订单用户
	 */
	public CouponResult checkThreeEndUser(OrderInfo orderInfo, Long productId) {
		CouponResult couponResult = new CouponResult(false, false);

		LocalDate today = LocalDate.now();

		boolean flag = false;

		String selectSql = "select id from t_product_info where label01 = '京华专标'";
		List<Map<String, Object>> results = this.jdbcTemplate.queryForList(selectSql);
		StringBuilder sb = new StringBuilder();
		sb.append("(");
		for (Map<String, Object> result: results) {
			sb.append(result.get("id") + ",");
		}
		sb = new StringBuilder(sb.substring(0, sb.length()-1));
		sb.append(")");

		String sql = String.format("select count(*) as count from t_order_info where orderCreatedOn >= ? and orderCreatedOn < ? and productId in %s", sb.toString());
		int count = this.jdbcTemplate.queryForObject(sql, new Object[]{
				Timestamp.valueOf(LocalDateTime.of(today, LocalTime.of(0, 0))).getTime(),
				orderInfo.getOrderCreatedOn()
		}, Integer.class).intValue();

		Parameter threeEndUser = parameterService.getByName(ThreeEndUser);
		Long total = Long.valueOf(threeEndUser.getValue01().trim());

		Parameter whatNumberEnd = parameterService.getByName(WhatNumberEnd);
		Long endNumber = Long.valueOf(whatNumberEnd.getValue01().trim());

		if (count < total.longValue()) {
			count = count + 1;
			if (count % 10 == endNumber.longValue()) {
				// 调用加息券的服务
				flag = true;
				Parameter newCardId = parameterService.getByName(ThreeEndEncourage);
				couponResult.setCount(this.getCoupon(orderInfo.getUserId(), Long.valueOf(newCardId.getValue01().trim()), orderInfo.getId()));
			}
		}

		couponResult.setFlag(flag);
		return couponResult;
	}

	/**
	 * 个人单日首笔购买“京华专项标”≥3000元，送30元京东E卡
	 */
	public CouponResult checkOneDayEncourage(OrderInfo orderInfo, Long productId) {
		CouponResult couponResult = new CouponResult(false, false);
		boolean flag = false;

		LocalDate today = LocalDate.now();
		String selectSql = "select id from t_product_info where label01 = '京华专标'";
		List<Map<String, Object>> results = this.jdbcTemplate.queryForList(selectSql);
		StringBuilder sb = new StringBuilder();
		sb.append("(");
		for (Map<String, Object> result: results) {
			sb.append(result.get("id") + ",");
		}
		sb = new StringBuilder(sb.substring(0, sb.length()-1));
		sb.append(")");

		Parameter oneDayMoney = parameterService.getByName(OneDayEncourageMoney);
		Long money = Long.valueOf(oneDayMoney.getValue01().trim());

		String sql = String.format(
				"select count(*) from t_order_info where productId in %s and userId = ? and orderCreatedOn >= ? and orderCreatedOn < ? and payStatus = 2 and realPayAmt >= %s order by orderCreatedOn desc",
				sb.toString(), oneDayMoney.getValue01().trim());

		Integer count = this.jdbcTemplate.queryForObject(sql, new Object[]{
				orderInfo.getUserId(),
				Timestamp.valueOf(LocalDateTime.of(today, LocalTime.of(0, 0))).getTime(),
				orderInfo.getOrderCreatedOn()
		}, Integer.class);

		if (count.intValue() == 0 && orderInfo.getRealPayAmt().doubleValue() >= money.longValue()) {
			flag = true;
			Parameter newCardId = parameterService.getByName(OneDayEncourage);
			couponResult.setCount(this.getCoupon(orderInfo.getUserId(), Long.valueOf(newCardId.getValue01().trim()), orderInfo.getId()));
		}

		couponResult.setFlag(flag);
		return couponResult;
	}

	/**
	 * 个人连续三天
	 */
	public CouponResult checkThreeComboEncourage(OrderInfo orderInfo, Long productId) {
		CouponResult couponResult = new CouponResult(false, false);
		Integer flag = 1;

		LocalDate today = LocalDate.now();
		LocalDate oneDayAgo = today.minusDays(1L);

		// 判断是否连续
		String selectSql = "select id from t_product_info where label01 = '京华专标'";
		List<Map<String, Object>> results = this.jdbcTemplate.queryForList(selectSql);
		StringBuilder sb = new StringBuilder();
		sb.append("(");
		for (Map<String, Object> result: results) {
			sb.append(result.get("id") + ",");
		}
		sb = new StringBuilder(sb.substring(0, sb.length()-1));
		sb.append(")");

		Parameter threeComboMoney = parameterService.getByName(ThreeComboEncourageMoney);
		Long money = Long.valueOf(threeComboMoney.getValue01());

		String sql = String.format("select count(*) as count from t_order_info where orderCreatedOn >= ? and orderCreatedOn < ? and userId= ? and realPayAmt >= %s and productId in %s order by orderCreatedOn desc",
				threeComboMoney.getValue01(), sb.toString());

		Integer count = this.jdbcTemplate.queryForObject(sql, new Object[] {
				Timestamp.valueOf(LocalDateTime.of(oneDayAgo, LocalTime.of(0, 0))).getTime(),
				Timestamp.valueOf(LocalDateTime.of(today, LocalTime.of(0, 0))).getTime(),
				orderInfo.getUserId()
		}, Integer.class);

		ActiveOrderRecord activeOrderRecord = this.activeOrderRecordService.query(orderInfo.getUserId(), productId);

		String firstSql = String.format("select count(*) as count from t_order_info where orderCreatedOn >= ? and orderCreatedOn < ? and userId = ? and realPayAmt >= %s and productId in %s",
				threeComboMoney.getValue01(), sb.toString());

		Integer firstCount = this.jdbcTemplate.queryForObject(firstSql, new Object[] {
				Timestamp.valueOf(LocalDateTime.of(today, LocalTime.of(0, 0))).getTime(),
				orderInfo.getOrderCreatedOn(),
				orderInfo.getUserId()
		}, Integer.class);

		if (count.intValue() > 0) {
			if (activeOrderRecord != null) {
				if (firstCount == 0) {
					Parameter threeComboEncourageTime = parameterService.getByName(ThreeComboEncourageTime);
					Integer threeTime = Integer.valueOf(threeComboEncourageTime.getValue01());

					if (orderInfo.getRealPayAmt().doubleValue() >= money.longValue()) {
						activeOrderRecord.setCount(activeOrderRecord.getCount() + 1);
						try {
							this.activeOrderRecordService.update(activeOrderRecord);
							if (activeOrderRecord.getCount() % threeTime.intValue() == 0) {
								Parameter newCardId = parameterService.getByName(ThreeComboEncourage);
								couponResult.setCount(this.getCoupon(orderInfo.getUserId(), Long.valueOf(newCardId.getValue01().trim()), orderInfo.getId()));
							}
						} catch (Exception e) {
							logger.info("jpa lock update error");
						}

					}
					flag = activeOrderRecord.getCount();
				} else {
					flag = 1;
				}
			} else {
				activeOrderRecord = new ActiveOrderRecord();
				activeOrderRecord.setCount(1);
				activeOrderRecord.setUserId(orderInfo.getUserId());
				activeOrderRecord.setProductId(productId);
				this.activeOrderRecordService.add(activeOrderRecord);
			}
		} else {
			if (firstCount == 0) {
				activeOrderRecord = new ActiveOrderRecord();
				activeOrderRecord.setCount(1);
				activeOrderRecord.setUserId(orderInfo.getUserId());
				activeOrderRecord.setProductId(productId);
				this.activeOrderRecordService.add(activeOrderRecord);
			} else {
				activeOrderRecord.setCount(1);
				activeOrderRecord.setUserId(orderInfo.getUserId());
				activeOrderRecord.setProductId(productId);
				this.activeOrderRecordService.update(activeOrderRecord);
			}



		}

		couponResult.setCouponCount(flag);
		return couponResult;
	}

	private boolean getCoupon(Long userId, Long cardId, Long orderId) {
		boolean flag = false;
		try {
			HttpClient httpClient = HttpClients.createDefault();

			String tokenUrl = String.format("%s/api/permission/token/%s", this.host, String.valueOf(userId));
			URI tokenUri = new URI(tokenUrl);
			HttpGet getMethod = new HttpGet(tokenUri);
			HttpResponse tokenResponse = httpClient.execute(getMethod);
			int tokenStatusCode = tokenResponse.getStatusLine().getStatusCode();
			if (tokenStatusCode == HttpStatus.SC_OK) {
				Gson gson = new Gson();

				String tokenBodyString = EntityUtils.toString(tokenResponse.getEntity());
				CouponJsonResult tokenJson = gson.fromJson(tokenBodyString, CouponJsonResult.class);
				if (tokenJson.getResultCode().equals("200")) {
					String token = (String)tokenJson.getResult();

					String url = String.format("%s/api/couponWallet/%s/add", host, userId);
					URI uri = new URI(url);
					HttpPost method = new HttpPost(uri);

					List<NameValuePair> nvps = new ArrayList<>();
					nvps.add(new BasicNameValuePair("cardId", String.valueOf(cardId)));
					nvps.add(new BasicNameValuePair("token", token));
					nvps.add(new BasicNameValuePair("orderId", String.valueOf(orderId)));

					method.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

					HttpResponse response = httpClient.execute(method);
					int statusCode = response.getStatusLine().getStatusCode();

					if(statusCode == HttpStatus.SC_OK) {
						String body = EntityUtils.toString(response.getEntity());
						logger.info("activity server: " + body);
						CouponJsonResult couponJsonResult = gson.fromJson(body, CouponJsonResult.class);
						if (couponJsonResult.getResultCode().equals("200")) {
							flag = true;
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("get coupon error: ", e);
		}

		return flag;
	}

	public OrderInfo findByOrderId(Long orderId) {
		OrderInfo orderInfo = this.orderService.findById(orderId);
		return orderInfo;
	}

	public static void main(String[] args) throws Exception {
		OrderHandleContent orderHandleContent = new OrderHandleContent();
		Long userId = Long.valueOf("72344298037649");

		//CheckInfo checkInfo = orderHandleContent.canBuy(userId);

		//System.out.println("checkINFo = " + checkInfo);
	}


	public OrderStrMsg getOrderStrMsgByView(OrderView orderView) {

		OrderStrMsg orderStrMsg = new OrderStrMsg();
		// 01加入订单基本属性
		orderStrMsg.setId(orderView.getOrderId().toString());
		orderStrMsg.setAmount(orderView.getSuccessAmount().toString());

		if(orderView.getNiggerAmount() != null){
			orderStrMsg.setNiggerAmount(orderView.getNiggerAmount().toString());
		}

		orderStrMsg.setPayStatus(orderView.getPayStatus().toString());
		orderStrMsg.setPayStatusStr(PayStatusEnum.getPayStatus(orderView.getPayStatus()));
		orderStrMsg.setConfirmStatus(orderView.getConfirmStatus().toString());
		orderStrMsg.setConfirmStatusStr(ConfirmStatusEnum.getConfirmStatus((orderView.getConfirmStatus())));


		orderStrMsg.setProductName(orderView.getProductName());

		//添加产品信息
		ProductInfo prod = productService.findById(orderView.getProductId());
		orderStrMsg.setProductCode(prod.getProNo());
		orderStrMsg.setProductCompanyId(prod.getIssuerId().toString());
		Company co = companyServie.findById(prod.getIssuerId());
		orderStrMsg.setProductCompanyName(co.getName());


		if(prod != null && prod.getParId() != null ){
			ProductInfo par = productService.findById(prod.getParId());
			if(par != null) {
				orderStrMsg.setProductParName(par.getName());
			}
		}

        // if user were closed acct , read back order table user name instead of user table
        if (StringUtils.isBlank(orderView.getUserRealName())) {
            OrderInfo orderInfo = orderService.findById(orderView.getOrderId());
            orderStrMsg.setUserName(orderInfo.getUserName());
        } else {
            orderStrMsg.setUserName(orderView.getUserRealName());
        }
		orderStrMsg.setCloseAccount(orderView.getCloseAccount());
        orderStrMsg.setUserPhoneNum(orderView.getUserPhone());
		orderStrMsg.setOrgName(orderView.getOrderOrgName());


		if (orderView.getFinUserId() != null) {
			SysUser finUser = userService.findById(orderView.getFinUserId());
			if (finUser != null) {
				orderStrMsg.setFinancialPlannerDepName(orderView.getOrderOrgName());
				orderStrMsg.setFinancialPlannerPhoneNum(orderView.getFinPhone());
				orderStrMsg.setFinancialPlannerName(orderView.getFinUserRealName());
				orderStrMsg.setFinancialPlannerId(orderView.getFinUserId().toString());
			}
		}

		orderStrMsg.setChannel(orderView.getOrderChannel().toString());
		UserChannel uc = userChannelService.findByChannelId(orderView.getOrderChannel());
		if(uc != null){
            orderStrMsg.setChannelName(uc.getName());
        }



		//3*合同相关附加信息
		orderStrMsg.setContractTitle(orderView.getContractTitle());
		orderStrMsg.setContractUrl(orderView.getContractUrl());
		orderStrMsg.setContractUrlHTML(orderView.getContractUrlHTML());

        orderStrMsg.setConfirmationTitle(orderView.getConfirmationTitle());
		orderStrMsg.setConfirmationHtml(orderView.getConfirmationHtml());
		orderStrMsg.setConfirmationPdf(orderView.getConfirmationPdf());




		//4*收益相关信息
		if(orderView.getProRate() != null) {
			orderStrMsg.setProRate(orderView.getProRate().toString());
		}

		if(orderView.getProdDividend() != null) {
			orderStrMsg.setProdDivendend(orderView.getProdDividend().toString());
		}


		if(orderView.getProdAddRate() != null) {
			orderStrMsg.setProdAddRate(orderView.getProdAddRate().toString());
		}

		if(orderView.getAddRateDividend() != null) {
			orderStrMsg.setAddRateDividend(orderView.getAddRateDividend().toString());
		}

		if (orderView.getUserCardId() != null) {
			orderStrMsg
					.setUserCardId(String.valueOf(orderView.getUserCardId()));
		}else{
			Long orderId = orderView.getOrderId();
			OrderInfo orderInfo = orderService.findById(orderId);
			if(orderInfo != null && orderInfo.getUserCardId() != null){
				orderStrMsg
						.setUserCardId(String.valueOf(orderInfo.getUserCardId()));
			}
		}

		if(orderView.getUserCardRate() != null) {
			orderStrMsg.setUserCardRate(orderView.getUserCardRate().toString());
		}
		if(orderView.getUserCardFaceValue() !=null){
			orderStrMsg.setUserCardFaceValue(orderView.getUserCardFaceValue());
		}

		//优惠券类型( 1,加息券; 2:体验金; 5:贴息券,)
		orderStrMsg.setBenefitType(orderView.getBenefitType());

		if(orderView.getUserCardDividend() != null) {
			orderStrMsg.setUserCardDividend(orderView.getUserCardDividend().toString());
		}

		if(orderView.getExtraTerm() != null) {
			orderStrMsg.setExtraTerm(orderView.getExtraTerm().toString());
		}


		if(orderView.getExtRate() != null ){
			orderStrMsg.setExtRate(orderView.getExtRate().toString());
		}

		if(orderView.getExtraDividend() != null) {
			orderStrMsg.setExtraDivendend(orderView.getExtraDividend().toString());
		}



		if (orderView.getSuccessAmount() != null) {
			orderStrMsg.setAmount(orderView.getSuccessAmount().toEngineeringString());
		} else {
			orderStrMsg.setAmount("");
		}
		orderStrMsg.setNiggerAmount(orderView.getNiggerAmount());


		if (orderView.getDividend() != null) {
			orderStrMsg.setDividend(orderView.getDividend().toString());
		}

		if (orderView.getExtraDividend() != null) {
			orderStrMsg.setExtraDivendend(String.valueOf(orderView
					.getExtraDividend()));
		}
		if (orderView.getProdDividend() != null) {
			orderStrMsg.setProdDivendend(String.valueOf(orderView
					.getProdDividend()));
		}

		if(orderView.getDividend() != null) {
			orderStrMsg.setDividend(orderView.getDividend().toString());
		}

		if(orderView.getTotalRate() != null) {
			orderStrMsg.setTotalRate(orderView.getTotalRate().toString());
		}

        //5*添加时间相关信息

        if (orderView.getOrderCreatedOn() != null) {
            orderStrMsg.setOrderCreatedOn(orderView.getOrderCreatedOn()
                    .toString());
            orderStrMsg.setOrderCreatedOnStr(DateUtil.longToLongDate(orderView
                    .getOrderCreatedOn()));
        }
        if (orderView.getOrderConfirmDate() != null) {
            orderStrMsg.setOrderConfirmDate(orderView.getOrderConfirmDate()
                    .toString());
            orderStrMsg.setOrderConfirmDateStr(DateUtil
                    .longToShortDate(orderView.getOrderConfirmDate()));
        }

        // 如果起息日不为空
        if (orderView.getOrderTradeDate() != null) {
            orderStrMsg.setOrderTradeDate(orderView.getOrderTradeDate()
                    .toString());
            orderStrMsg.setOrderTradeDateStr(DateUtil.longToShortDate(orderView
                    .getOrderTradeDate()));
        } else {
            // 如果起息日为空
            orderStrMsg.setOrderTradeDate(null);
            orderStrMsg.setOrderTradeDateStr("");
        }

        // 如果回款日不为空
        if (orderView.getDividendDate() != null) {
            orderStrMsg.setOrderDividendDate(orderView.getDividendDate()
                    .toString());
            orderStrMsg.setOrderDividendDateStr(DateUtil
                    .longToShortDate(orderView.getDividendDate()));
        } else {
            // 如果回款日为空
            orderStrMsg.setOrderDividendDate(null);
            orderStrMsg.setOrderDividendDateStr("");
        }

        //预计清算时间
        if(orderView.getClearDate() !=null){
			orderStrMsg.setClearDate(DateUtil.longToLongDate(orderView.getClearDate().getTime()));
		}

		//是否定向
		if(orderView.getDirectional() != null){
        	orderStrMsg.setDirectional(orderView.getDirectional()== 1?"是":"否");
		}


		//7*银行卡相关信息
//		orderStrMsg.setPaymentBankCardNo(orderView.getPaymentNo());
//		orderStrMsg.setPaymentBankName(orderView.getBankName());
//		orderStrMsg.setIdentity(orderView.getIdentityNo());

		OrderInfo orderInfo = orderService.findById(orderView.getOrderId());
		Payment payment = paymentService.getPaymentInfo(orderInfo.getUserId(), orderInfo.getPaymentId());

		if(payment != null){
			orderStrMsg.setPaymentBankCardNo(payment.getPaymentNo());
			orderStrMsg.setPaymentBankName(payment.getBankName());
			orderStrMsg.setPaymentSubBankName(orderInfo.getSubBankName());
			orderStrMsg.setPaymentUserName(payment.getAccountName());
			orderStrMsg.setIdentity(payment.getIdentityNo());
		}



        if(orderView.getTerm() != null){
            orderStrMsg.setTerm(orderView.getTerm().toString());
        }

		if(orderView.getPaymentId().toString().equals(ConstantPayment.FYJZH_PAY)){
			orderStrMsg.setOrderType("金账户扣款");
		}else{
			orderStrMsg.setOrderType("代扣扣款");
		}
		orderStrMsg.setSubBankName(orderView.getSubBankName());
		orderStrMsg.setKycUrl(orderView.getKycUrl());
		orderStrMsg.setRiskLevel(orderView.getRiskLevel());

		return orderStrMsg;
	}
}
